package com.xinchao.ck_mips.utils;

import android.text.TextUtils;

import com.xinchao.devicemanage.util.MD5Util;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Set;
import java.util.TreeSet;

import okhttp3.Request;
import okhttp3.RequestBody;
import okio.Buffer;

/**
 * @author: JessieKate
 * @date: 2018/10/25
 * @email: lyj1246505807@gmail.com
 * @description: 签名工具类
 */

public class SignUtil {

    /**
     * @param originalRequest 请求对象
     * @param curtime         当前时间戳
     * @return
     * @throws IOException
     */
    public static String getSign(Request originalRequest, long curtime) throws IOException {
        RequestBody body = originalRequest.body();
        String postPath = originalRequest.url().url().getFile();
        Buffer buffer = new Buffer();
        body.writeTo(buffer);
        String oldParamsJson = buffer.readUtf8();
//              Logger.t(DeviceConstant.qiangTag).d("自然排序前：" + oldParamsJson);
        oldParamsJson = URLDecoder.decode(oldParamsJson);
//              Logger.t(DeviceConstant.qiangTag).d("自然排序前decode:" + oldParamsJson);
        Set<String> paramNames = new TreeSet<String>(); // 使用treeset 自然排序

        // 如果老参数不为空，自然排序
        if (!TextUtils.isEmpty(oldParamsJson)) {
            String[] params = oldParamsJson.split("&");
            for (int i = 0; i < params.length; i++) {
                paramNames.add(params[i]);
            }
        }
        paramNames.add("timestamp=" + curtime);
        // 初始化待md5签名字符串
        StringBuilder retVal = new StringBuilder(postPath);
        int count = 0;
        for (String name : paramNames) {
            if (count++ > 0) {
                retVal.append("&");
            } else {
                retVal.append("@");
            }
            retVal.append(name);
        }
        oldParamsJson = retVal.toString();
        return MD5Util.getStringMD5(oldParamsJson);
    }
}
